import os
import json

def read_json_file(json_file):
    if not os.path.exists(json_file):
        return []
    with open(json_file, 'r') as f:
        ret = json.load(f)
    return ret

def write_json_file(json_file, content):
    path = os.path.dirname(json_file)
    if not os.path.exists(path):
        os.makedirs(path)
    with open(json_file, 'w') as f:
        json.dump(content, f, indent=4)

filename = 'compile_commands.json'

YSYX_HOME = os.environ['YSYX_HOME']
# NEMU
NEMU_HOME = os.path.join(YSYX_HOME, "nemu")
# NPC
NPC_HOME = os.path.join(YSYX_HOME, "npc")
# AM
AM_HOME = os.path.join(YSYX_HOME, "abstract-machine", "am")
KLIB_HOME = os.path.join(YSYX_HOME, "abstract-machine", "klib")
# NACY-APPS
NAVY_HOME = os.path.join(YSYX_HOME, "navy-apps")
LIBC_HOME = os.path.join(NAVY_HOME, "libs", "libc")
LIBOS_HOME = os.path.join(NAVY_HOME, "libs", "libos")
LIBNDL_HOME = os.path.join(NAVY_HOME, "libs", "libndl")
LIBFIXEDPTC_HOME = os.path.join(NAVY_HOME, "libs", "libfixedptc")
LIBMINISDL_HOME = os.path.join(NAVY_HOME, "libs", "libminiSDL")
# NANOS-LITE
NANOS_HOME = os.path.abspath(os.path.join(YSYX_HOME, "nanos-lite"))

# nemu 
nemu = read_json_file(os.path.join(NEMU_HOME, filename))

# npc
npc = read_json_file(os.path.join(NPC_HOME, filename))

# am
am = read_json_file(os.path.join(AM_HOME, filename))
klib = read_json_file(os.path.join(KLIB_HOME, filename))

# nanos-lite
nanos = read_json_file(os.path.join(NANOS_HOME, filename))

# navy-apps
libc = read_json_file(os.path.join(LIBC_HOME, filename))
libos = read_json_file(os.path.join(LIBOS_HOME, filename))
libndl = read_json_file(os.path.join(LIBNDL_HOME, filename))
libfixedptc = read_json_file(os.path.join(LIBFIXEDPTC_HOME, filename))
libminiSDL = read_json_file(os.path.join(LIBMINISDL_HOME, filename))

result = nemu + npc + am + klib + nanos + libc + libos + libndl + libfixedptc + libminiSDL

output_path = os.path.abspath(YSYX_HOME)
write_json_file(os.path.join(output_path, filename), result)

print("merged file is " + output_path + "/compile_commands.json")